package com.pzb.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.pzb.common.core.domain.AjaxResult;
import com.pzb.common.utils.MakeOrderNumUtil;
import com.pzb.common.utils.StringUtils;
import com.pzb.goods.domain.GdFreightTemplateData;
import com.pzb.goods.domain.GdGoods;
import com.pzb.goods.domain.GdGoodsUnits;
import com.pzb.goods.service.IGdGoodsService;
import com.pzb.market.domain.MkCoupon;
import com.pzb.market.domain.MkDiscount;
import com.pzb.market.domain.MkIntegralSetting;
import com.pzb.market.service.IMkCouponService;
import com.pzb.market.service.IMkDiscountService;
import com.pzb.market.service.IMkIntegralSettingService;
import com.pzb.order.domain.CheckOutModel;
import com.pzb.order.domain.OdOrder;
import com.pzb.order.domain.OdOrderDetail;
import com.pzb.order.domain.OdOrderSetting;
import com.pzb.order.mapper.OdOrderMapper;
import com.pzb.order.service.IOdOrderDetailService;
import com.pzb.order.service.IOdOrderService;
import com.pzb.order.service.IOdOrderSettingService;
import com.pzb.rabbitmq.RabbitMqModel;
import com.pzb.rabbitmq.RabbitMqSender;
import com.pzb.wechat.domain.*;
import com.pzb.wechat.service.*;
import com.pzb.wxpay.service.IWxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 订单管理Service业务层处理
 * 
 * @author Mr_Wu
 * @date 2021-12-15
 */
@Service
public class OdOrderServiceImpl implements IOdOrderService 
{
    @Autowired
    private OdOrderMapper odOrderMapper;
    @Autowired
    private IOdOrderSettingService orderSettingService;
    @Autowired
    private IOdOrderDetailService orderDetailService;
    @Autowired
    private IWechatUserAccountService userAccountService;
    @Autowired
    private IWechatShoppingCartService wechatShoppingCartService;
    @Autowired
    private IWechatUserCouponService wechatUserCouponService;
    @Autowired
    private IWxPayService wxPayService;
    @Autowired
    private IGdGoodsService gdGoodsService;
    @Autowired
    private IWechatAddressService wechatAddressService;
    @Autowired
    private IMkIntegralSettingService integralSettingService;
    @Autowired
    private IMkCouponService couponService;
    @Autowired
    private IWechatPickupSettingService pickupSettingService;
    @Autowired
    private IMkDiscountService discountService;
    @Autowired
    private RabbitMqSender rabbitMqSender;


    @Override
    public AjaxResult createOrder(CheckOutModel model) {
        //自提设置
        WechatPickupSetting pickupSetting = pickupSettingService.selectWechatPickupSetting(model.getExtAppid());
        //默认收货地址
        WechatAddress wechatAddress = wechatAddressService.selectWechatDefaultAddress(model.getOpenid(), model.getExtAppid());
        String  provinceCode = "";
        if(wechatAddress!=null){
            JSONArray provinceArray = JSON.parseArray(wechatAddress.getProvince());
            provinceCode = provinceArray.getJSONObject(0).getString("value");
        }
        //运费
        double  expressAmount = 0;

        //用户未使用的优惠券列表
        List<WechatUserCoupon> userCouponList = wechatUserCouponService.selectWechatUserCouponList(model.getExtAppid(), model.getOpenid(),"isUnused");
        //使用的优惠券
        MkCoupon couponUse = null;
        if(model.getCouponId() != null && model.getCouponId() != 0){
            couponUse = couponService.selectMkCouponById(model.getCouponId());
        }
        //商家开放的店铺活动列表
        List<MkDiscount> discountList = discountService.selectProgressDiscountList(model.getExtAppid());

        MkDiscount discount = null;
        if(model.getDiscountId() != null && model.getDiscountId() != 0){
            discount =discountService.selectMkDiscountById(model.getDiscountId());
        }

        //立即购买
        OdOrder order = new OdOrder();
        order.setExtAppid(model.getExtAppid());
        order.setOpenid(model.getOpenid());
        order.setCreateTime(new Date());
        order.setWechatAddress(wechatAddress);
        order.setDeliveryMethod(model.getDelivery());
        order.setPickupSetting(pickupSetting);
        order.setUserIntegral(model.getIsUsePoints());
        //初始化优惠数据
        order.setCouponId(0L);
        order.setCouponAmount("0");
        order.setDiscountId(0L);
        order.setDiscountAmount("0");
        order.setExpressAmount("0");
        //本订单可使用优惠券
        List<WechatUserCoupon> couponList=new ArrayList<>();
        //本订单可使用优惠券
        List<MkDiscount> discountList1 = new ArrayList<>();

        if("buyNow".equals(model.getMode())){
            //查询该规格商品库存
            GdGoodsUnits goodsUnit = gdGoodsService.selectGoodsUnitsById(model.getGoodsUnitId());
            //如果库存不足 返回错误
            if(model.getQuantity().intValue() > goodsUnit.getStock().intValue()){
                return AjaxResult.error("商品库存不足！");
            }
            GdGoods goods = gdGoodsService.selectGdGoodsById(model.getGoodsId(),model.getExtAppid(),provinceCode);
            //金额为商品单价*商品数量
            String amount = (new BigDecimal(model.getQuantity()).multiply(new BigDecimal(model.getPrice()))).toString();
            order.setTotalQuantity(model.getQuantity());
            order.setTotalAmount(amount);
            order.setPayTotalAmount(amount);
            OdOrderDetail orderDetail=new OdOrderDetail();
            orderDetail.setGoodsUnitId(goodsUnit.getId());
            orderDetail.setExtAppid(model.getExtAppid());
            orderDetail.setGoodsName(goods.getName());
            orderDetail.setGoodsId(model.getGoodsId());
            orderDetail.setGoodsUnit(model.getGoodsUnit());
            orderDetail.setQuantity(model.getQuantity());
            orderDetail.setPrice(model.getPrice());
            orderDetail.setAmount(amount);
            orderDetail.setPicturePath(goods.getPicturePath());
            orderDetail.setCouponAmount("0");
            orderDetail.setDiscountAmount("0");
            orderDetail.setExpressAmount("0");
            //如果使用了优惠券
            if (couponUse != null){
                if("0".equals(couponUse.getType())){//代金券
                    order.setPayTotalAmount((new BigDecimal(order.getTotalAmount()).subtract(couponUse.getDeductionAmount())).toString());
                }else if("1".equals(couponUse.getType())){//折扣券
                    order.setPayTotalAmount(new BigDecimal(order.getTotalAmount()).multiply(couponUse.getDeductionAmount()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                }
                order.setCouponId(model.getUserCouponId());
                //优惠券优惠金额
                String couponAmount = new BigDecimal(order.getTotalAmount()).subtract(new BigDecimal(order.getPayTotalAmount())).toString();
                order.setCouponAmount(couponAmount);
                orderDetail.setCouponAmount(couponAmount);
            }
            //活动免运费 初始值false
            boolean expressFree = false;
            //如果参加了店铺活动
            if (discount != null){
                order.setDiscountId(discount.getId());
                order.setDiscount(discount);
                if("0".equals(discount.getType())){ //满减
                    order.setDiscountAmount(discount.getDeductionAmount().toString());
                    order.setPayTotalAmount(new BigDecimal(order.getPayTotalAmount()).subtract(discount.getDeductionAmount()).toString());
                    orderDetail.setDiscountAmount(discount.getDeductionAmount().toString());
                }else if("1".equals(discount.getType())){ //满折
                    //折后金额
                    BigDecimal  payAmount = new BigDecimal(order.getPayTotalAmount()).multiply(discount.getDeductionAmount()).setScale(2,BigDecimal.ROUND_HALF_UP);
                    //折扣金额
                    String disAmount = new BigDecimal(order.getPayTotalAmount()).subtract(payAmount).toString();
                    order.setDiscountAmount(disAmount);
                    order.setPayTotalAmount(payAmount.toString());
                    orderDetail.setDiscountAmount(disAmount);

                }else if("2".equals(discount.getType())){ //满包邮
                    expressFree = true;
                }
            }
            List<OdOrderDetail> detailList = new ArrayList<>();
            detailList.add(orderDetail);
            //可用优惠券
            for (WechatUserCoupon coupon : userCouponList) {
                //如果金额大于优惠券指定金额
                if(("0".equals(coupon.getUnit()) && new BigDecimal(amount).compareTo(coupon.getAvailableAmount())>=0)||("1".equals(coupon.getUnit()) && order.getTotalQuantity().intValue() >= coupon.getAvailableAmount().intValue())){
                    if("0".equals(coupon.getAvailableGoods())){//全部商品
                        couponList.add(coupon);
                    }else if("1".equals(coupon.getAvailableGoods()) && coupon.getClassIds()!=null){//指定分类
                        if(coupon.getClassIds().contains(goods.getGoodsClassId())){
                            couponList.add(coupon);
                        }
                    }else if("2".equals(coupon.getAvailableGoods()) && coupon.getGoodsIds()!=null){//指定商品
                        if(coupon.getGoodsIds().contains(model.getGoodsId())){
                            couponList.add(coupon);
                        }
                    }
                }
            }
            //可参与店铺活动
            for (MkDiscount mkDiscount : discountList) {
                if(!"4".equals(mkDiscount.getType())){ //如果不是充值活动
                    //如果金额大于优惠券指定金额
                    if(("0".equals(mkDiscount.getUnit()) && new BigDecimal(order.getPayTotalAmount()).compareTo(mkDiscount.getAvailableAmount())>=0)||("1".equals(mkDiscount.getUnit()) && order.getTotalQuantity().intValue() >= mkDiscount.getAvailableAmount().intValue())){
                        if("0".equals(mkDiscount.getAvailableGoods())){//全部商品
                            discountList1.add(mkDiscount);
                        }else if("1".equals(mkDiscount.getAvailableGoods()) && mkDiscount.getClassIds()!=null){//指定分类
                            if(mkDiscount.getClassIds().contains(goods.getGoodsClassId())){
                                discountList1.add(mkDiscount);
                            }
                        }else if("2".equals(mkDiscount.getAvailableGoods()) && mkDiscount.getGoodsIds()!=null){//指定商品
                            if(mkDiscount.getGoodsIds().contains(model.getGoodsId())){
                                discountList1.add(mkDiscount);
                            }
                        }
                    }
                }
            }
            //计算运费
            //地址不为空 & 无活动包邮 计算运费
            if(wechatAddress!=null && !expressFree){
                GdFreightTemplateData templateData = goods.getFreightTemplate();
                if("0".equals(templateData.getType())){ //包邮
                    expressAmount = 0;
                }else if("1".equals(templateData.getType())){ //不包邮
                    if("0".equals(templateData.getTemplateType())){ //按件计费
                        //判断是否满足包邮条件
                        if("0".equals(templateData.getAppoint()) && order.getTotalQuantity() >= templateData.getAppointValue()){
                            expressAmount = 0;
                        }else {
                            //首次计费
                            expressAmount = templateData.getFirstAmount().doubleValue();
                            //超出计费
                            //超出数量
                            int extCount = order.getTotalQuantity() - templateData.getFirstValue();
                            if(extCount > 0){ //如果超出
                                //计算超出条件倍数
                                int c = extCount/templateData.getOtherValue();
                                if(extCount%templateData.getOtherValue()>0){
                                    c+=1;
                                }
                                //超出金额
                                expressAmount+=c * templateData.getOtherAmount().doubleValue();
                            }
                        }
                    }
                }
            }
            order.setOrderDetailList(detailList);

        }else if("cart".equals(model.getMode())){
            //根据购物车id查询商品信息
            List<WechatShoppingCart> cartList = wechatShoppingCartService.selectWechatShoppingCartListByIds(model.getExtAppid(),model.getCartIds(),provinceCode);
            List<OdOrderDetail> detailList = new ArrayList<>();
            Integer totalQuantity = 0;
            String totalAmount = "0";
            for (WechatShoppingCart cart : cartList) {
                //库存验证
                if(cart.getNumber().intValue() > cart.getStock()){
                    return AjaxResult.error(cart.getGoodsName()+"库存不足！");
                }

                OdOrderDetail orderDetail=new OdOrderDetail();
                orderDetail.setExtAppid(model.getExtAppid());
                orderDetail.setGoodsName(cart.getGoodsName());
                orderDetail.setCartId(cart.getId());
                orderDetail.setGoodsId(cart.getGoodsId());
                orderDetail.setGoodsUnitId(cart.getGoodsUnitId());
                //暂存 用于下方优惠券指定分类包含判断
                orderDetail.setClassId(cart.getClassId());
                orderDetail.setGoodsUnit(cart.getGoodsUnit());
                orderDetail.setQuantity(cart.getNumber());
                orderDetail.setPrice(cart.getPrice());
                //设置优惠默认值
                orderDetail.setCouponAmount("0");
                orderDetail.setDiscountAmount("0");
                orderDetail.setIntegralAmount("0");
                BigDecimal amount = new BigDecimal(cart.getNumber()).multiply(new BigDecimal(cart.getPrice()));
                orderDetail.setAmount(amount.toString());
                orderDetail.setPicturePath(cart.getPicturePath());
                totalQuantity+=cart.getNumber();
                totalAmount=(new BigDecimal(totalAmount).add(amount)).toString();
                //分配商品对应优惠券
                for (WechatUserCoupon coupon : userCouponList) {
                    if("0".equals(coupon.getAvailableGoods())){//全部商品
                        coupon.getOrderDetailList().add(orderDetail);
                    }else if("1".equals(coupon.getAvailableGoods()) && coupon.getClassIds()!=null){//指定分类
                        if (coupon.getClassIds().contains(orderDetail.getClassId())){
                            coupon.getOrderDetailList().add(orderDetail);
                        }
                    }else if("2".equals(coupon.getAvailableGoods()) && coupon.getGoodsIds()!=null){//指定商品
                        if (coupon.getGoodsIds().contains(orderDetail.getGoodsId())){
                            coupon.getOrderDetailList().add(orderDetail);
                        }
                    }
                }
                //分配商品对应店铺活动
                for (MkDiscount discount1 : discountList) {
                    if(!"4".equals(discount1.getType())) { //如果不是充值活动
                        if ("0".equals(discount1.getAvailableGoods())) {//全部商品
                            discount1.getOrderDetailList().add(orderDetail);
                        } else if ("1".equals(discount1.getAvailableGoods()) && discount1.getClassIds() != null) {//指定分类
                            if (discount1.getClassIds().contains(orderDetail.getClassId())) {
                                discount1.getOrderDetailList().add(orderDetail);
                            }
                        } else if ("2".equals(discount1.getAvailableGoods()) && discount1.getGoodsIds() != null) {//指定商品
                            if (discount1.getGoodsIds().contains(orderDetail.getGoodsId())) {
                                discount1.getOrderDetailList().add(orderDetail);
                            }
                        }
                    }
                }
                //计算运费
                if(wechatAddress!=null){
                    GdFreightTemplateData templateData = cart.getFreightTemplate();
                    double cartExpressAmount = 0;
                    if("1".equals(templateData.getType())){ //不包邮
                        if("0".equals(templateData.getTemplateType())){ //按件计费
                            //判断是否满足包邮条件
                            if("0".equals(templateData.getAppoint()) && cart.getNumber() >= templateData.getAppointValue()){
                                cartExpressAmount = 0;
                            }else {
                                //首次计费
                                cartExpressAmount = templateData.getFirstAmount().doubleValue();
                                //超出计费
                                //超出数量
                                int extCount = cart.getNumber() - templateData.getFirstValue();
                                if(extCount > 0){ //如果超出
                                    //计算超出条件倍数
                                    int c = extCount/templateData.getOtherValue();
                                    if(extCount%templateData.getOtherValue()>0){
                                        c+=1;
                                    }
                                    //超出金额
                                    cartExpressAmount+=c * templateData.getOtherAmount().doubleValue();
                                }
                            }

                        }
                    }
                    orderDetail.setExpressAmount(String.valueOf(cartExpressAmount));
                }
                detailList.add(orderDetail);
            }

            WechatUserCoupon userCoupon = null;
            //计算优惠券是否满足触发条件
            for (WechatUserCoupon coupon : userCouponList) {
                BigDecimal goodsAmount = new BigDecimal(0.00);
                Integer goodsCount = 0;
                //优惠券订单总价 件数
                for (OdOrderDetail orderDetail : coupon.getOrderDetailList()) {
                    goodsAmount = goodsAmount.add(new BigDecimal(orderDetail.getAmount()));
                    goodsCount+= orderDetail.getQuantity();
                }
                if(("0".equals(coupon.getUnit()) && goodsAmount.compareTo(coupon.getAvailableAmount())>=0) || ("1".equals(coupon.getUnit()) && goodsCount.intValue() >= coupon.getAvailableAmount().intValue())){
                    couponList.add(coupon);
                }
                if(couponUse!=null && couponUse.getId().longValue() == coupon.getCouponId().longValue()){
                    userCoupon=coupon;
                }
            }

            MkDiscount useDiscount = null;
            //计算店铺活动是否满足触发条件
            for (MkDiscount discount1 : discountList) {
                BigDecimal goodsAmount = new BigDecimal(0.00);
                Integer goodsCount = 0;
                //优惠券订单总价 件数
                for (OdOrderDetail orderDetail : discount1.getOrderDetailList()) {
                    goodsAmount = goodsAmount.add(new BigDecimal(orderDetail.getAmount()));
                    goodsCount+= orderDetail.getQuantity();
                }
                if(("0".equals(discount1.getUnit()) && goodsAmount.compareTo(discount1.getAvailableAmount())>=0) || ("1".equals(discount1.getUnit()) && goodsCount.intValue() >= discount1.getAvailableAmount().intValue())){
                    discountList1.add(discount1);
                }
                if(discount!=null && discount.getId().longValue() == discount1.getId().longValue()){
                    useDiscount=discount1;
                }
            }
            order.setCouponList(couponList);
            order.setDiscountList(discountList1);
            order.setTotalQuantity(totalQuantity);
            order.setTotalAmount(totalAmount);
            order.setPayTotalAmount(totalAmount);

            //如果使用优惠券
            if(userCoupon != null){
                //参与优惠商品的总金额
                BigDecimal couponGoodsAmount = new BigDecimal(0.00) ;
                for (OdOrderDetail odOrderDetail : userCoupon.getOrderDetailList()) {
                    couponGoodsAmount = couponGoodsAmount.add(new BigDecimal(odOrderDetail.getAmount()));
                }
                //计算优惠金额  并将优惠金额分配到每个商品
                BigDecimal couponAmount =new BigDecimal(0.00);
                if("0".equals(couponUse.getType())){//代金券
                    couponAmount = couponUse.getDeductionAmount();
                }else if("1".equals(couponUse.getType())){//折扣券
                    couponAmount = couponGoodsAmount.subtract(couponGoodsAmount.multiply(couponUse.getDeductionAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
                }
                order.setCouponId(model.getUserCouponId());
                order.setCouponAmount(String.valueOf(couponAmount));
                order.setPayTotalAmount(String.valueOf(new BigDecimal(order.getPayTotalAmount()).subtract(couponAmount)));
                //分配优惠券金额
                for (int i = 0; i < userCoupon.getOrderDetailList().size(); i++) {
                    //如果最后一个做减法运算  防止乘法四舍五入 总优惠金额出现误差
                    if(i == userCoupon.getOrderDetailList().size()-1){
                        for (OdOrderDetail odOrderDetail : detailList) {
                            if(userCoupon.getOrderDetailList().get(i).getCartId().longValue() == odOrderDetail.getCartId().longValue()){
                                odOrderDetail.setCouponAmount(String.valueOf(couponAmount));
                                break;
                            }
                        }
                    }else {
                        BigDecimal gdCouponAmount = couponAmount.multiply( new BigDecimal(userCoupon.getOrderDetailList().get(i).getAmount()).divide(couponGoodsAmount,2,BigDecimal.ROUND_HALF_UP)).setScale(2,BigDecimal.ROUND_HALF_UP);
                        for (OdOrderDetail odOrderDetail : detailList) {
                            if(userCoupon.getOrderDetailList().get(i).getCartId().longValue() == odOrderDetail.getCartId().longValue()){
                                odOrderDetail.setCouponAmount(String.valueOf(gdCouponAmount));
                                couponAmount = couponAmount.subtract(gdCouponAmount);
                            }
                        }

                    }
                }
            }

            //如果参与店铺活动
            if(useDiscount != null){
                //参与店铺活动商品的总金额 //使用优惠券后的金额
                BigDecimal discountGoodsAmount = new BigDecimal(0.00) ;
                for (OdOrderDetail odOrderDetail : useDiscount.getOrderDetailList()) {
                    //金额为商品金额减优惠券金额 当前detailList集合中包含优惠券金额
                    for (OdOrderDetail detail : detailList) {
                        if(odOrderDetail.getCartId().longValue() == detail.getCartId().longValue()){
                            discountGoodsAmount = discountGoodsAmount.add(new BigDecimal(detail.getAmount()).subtract(new BigDecimal(detail.getCouponAmount())));
                            odOrderDetail.setCouponAmount(detail.getCouponAmount());
                            break;
                        }
                    }

                }
                //计算活动金额  并将活动金额分配到每个商品
                BigDecimal discountAmount =new BigDecimal(0.00);
                if("0".equals(useDiscount.getType())){//代金券
                    discountAmount = useDiscount.getDeductionAmount();
                }else if("1".equals(useDiscount.getType())){//折扣券
                    discountAmount = discountGoodsAmount.subtract(discountGoodsAmount.multiply(useDiscount.getDeductionAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
                }
                order.setDiscountId(useDiscount.getId());
                order.setDiscountAmount(String.valueOf(discountAmount));
                order.setPayTotalAmount(String.valueOf(new BigDecimal(order.getPayTotalAmount()).subtract(discountAmount)));

                //分配店铺活动金额
                for (int i = 0; i < useDiscount.getOrderDetailList().size(); i++) {
                    //如果是包邮活动
                    if("2".equals(useDiscount.getType())){
                        for (OdOrderDetail odOrderDetail : detailList) {
                            if(useDiscount.getOrderDetailList().get(i).getCartId().longValue() == odOrderDetail.getCartId().longValue()){
                                odOrderDetail.setExpressAmount("0");
                                break;
                            }
                        }

                    }else if(!"4".equals(useDiscount.getType())){ //如果是满减或满折
                        //如果最后一个做减法运算  防止乘法四舍五入 总优惠金额出现误差
                        if(i == useDiscount.getOrderDetailList().size()-1){
                            for (OdOrderDetail odOrderDetail : detailList) {
                                if(useDiscount.getOrderDetailList().get(i).getCartId().longValue() == odOrderDetail.getCartId().longValue()){
                                    odOrderDetail.setDiscountAmount(String.valueOf(discountAmount));
                                    break;
                                }
                            }
                        }else {
                            OdOrderDetail detail = useDiscount.getOrderDetailList().get(i);
                            BigDecimal gdDiscountAmount = discountAmount.multiply( new BigDecimal(detail.getAmount()).subtract(new BigDecimal(detail.getCouponAmount())).divide(discountGoodsAmount,2,BigDecimal.ROUND_HALF_UP)).setScale(2,BigDecimal.ROUND_HALF_UP);
                            for (OdOrderDetail odOrderDetail : detailList) {
                                if(detail.getCartId().longValue() == odOrderDetail.getCartId().longValue()){
                                    odOrderDetail.setDiscountAmount(String.valueOf(gdDiscountAmount));
                                    discountAmount = discountAmount.subtract(gdDiscountAmount);
                                }
                            }
                        }
                    }
                }
            }

            //计算运费  多件商取价格最高
            for (OdOrderDetail odOrderDetail : detailList) {
                if(Double.parseDouble(odOrderDetail.getExpressAmount())>expressAmount){
                    expressAmount = Double.parseDouble(odOrderDetail.getExpressAmount());
                }
            }
            order.setOrderDetailList(detailList);
        }

        order.setCouponList(couponList);
        order.setDiscountList(discountList1);
        //账户信息
        WechatUserAccount account = userAccountService.selectWechatUserAccountByOpenId(model.getOpenid(),model.getExtAppid());
        //查询店铺积分设置
        MkIntegralSetting integralSetting = integralSettingService.selectMkIntegralSetting(model.getExtAppid());
        order.setIntegralSetting(integralSetting);
        //计算可用积分
        if("0".equals(integralSetting.getStatus())){//如果开启积分
            //可用积分  //去除积分倍数的余数
            long availablePoint = account.getIntegral() - (account.getIntegral()%integralSetting.getDeduction());
            //如果限制单订单使用数量
            if("1".equals(integralSetting.getDeductionLimit()) && availablePoint > integralSetting.getLimitQuantity().intValue()){
                availablePoint = integralSetting.getLimitQuantity();
            }
            //计算积分抵扣金额是否超过订单金额
            //积分抵扣金额 单位元
            BigDecimal integralAmount = new BigDecimal(availablePoint).divide(new BigDecimal(integralSetting.getDeduction()),0,BigDecimal.ROUND_HALF_DOWN);

            //如果积分抵扣金额大于商品订单金额
            if(integralAmount.compareTo(new BigDecimal(order.getPayTotalAmount()))>0){
                //按订单金额计算
                //去除小数为抵扣金额
                integralAmount = new BigDecimal(order.getPayTotalAmount()).divide(new BigDecimal(1),0,BigDecimal.ROUND_HALF_DOWN);
            }
            //防止商家设置的不是倍数导致积分数量与抵扣金额不一直 重新计算使用积分 抵扣金额* N积分抵扣1元
            availablePoint = integralAmount.multiply(new BigDecimal(integralSetting.getDeduction())).longValue();
            order.setIntegral(availablePoint);
            order.setIntegralAmount(integralAmount.toString());
            //如果使用积分 进行积分抵扣
            if(order.getUserIntegral().intValue() == 1){
                order.setPayTotalAmount(new BigDecimal(order.getPayTotalAmount()).subtract(integralAmount).toString());
                //积分分配到每个商品
                for (int i = 0; i < order.getOrderDetailList().size(); i++) {
                    //如果最后一个做减法运算  防止乘法四舍五入 总优惠金额出现误差
                    if(i == order.getOrderDetailList().size()-1){
                        order.getOrderDetailList().get(i).setIntegralAmount(String.valueOf(integralAmount));
                    }else {
                        OdOrderDetail detail = order.getOrderDetailList().get(i);
                        BigDecimal payAmount = new BigDecimal(detail.getAmount()).subtract(new BigDecimal(detail.getCouponAmount())).subtract(new BigDecimal(detail.getDiscountAmount()));
                        BigDecimal gdIntegralAmount = integralAmount.multiply(payAmount.divide(new BigDecimal(order.getTotalAmount()).subtract(new BigDecimal(order.getCouponAmount())).subtract(new BigDecimal(order.getDiscountAmount())),2,BigDecimal.ROUND_HALF_UP)).setScale(2,BigDecimal.ROUND_HALF_UP);
                        detail.setIntegralAmount(String.valueOf(gdIntegralAmount));
                        integralAmount = integralAmount.subtract(gdIntegralAmount);
                    }
                }
            }
        }
        //快递配送费用
        order.setExpressAmount(String.valueOf(expressAmount));//
        if(expressAmount>0){
            order.setPayTotalAmount(new BigDecimal(order.getPayTotalAmount()).add(new BigDecimal(expressAmount)).toString());
        }
        //如果账户余额大于订单金额 默认余额支付
        if (new BigDecimal(account.getBalance()).compareTo(new BigDecimal(order.getPayTotalAmount()))>=0) {
            order.setPaymentMethod("0");
        }else {
            order.setPaymentMethod("1");
        }
        AjaxResult result = AjaxResult.success();
        result.put("order",order);
        result.put("personal",account);
        return result;
    }


    @Override
    public int insertOdOrder(OdOrder odOrder) {
        return odOrderMapper.insertOdOrder(odOrder);
    }

    /**
     * 查询订单管理
     * 
     * @param id 订单管理主键
     * @return 订单管理
     */
    @Override
    public OdOrder selectOdOrderById(Long id)
    {
        OdOrder order = odOrderMapper.selectOdOrderById(id);
        //查询赠品
        if(order.getDiscountId()!=null && order.getDiscountId().longValue()>0){
            MkDiscount discount = discountService.selectMkDiscountById(order.getDiscountId());
            //如果是送赠品
            if("3".equals(discount.getType())){
                List<GdGoods> giftList = gdGoodsService.selectGiftListByDiscountId(discount.getId());
                discount.setGiftList(giftList);
                order.setDiscount(discount);
            }
        }
        List<OdOrderDetail> detailList = orderDetailService.selectOdOrderDetailByOrderCode(order.getOrderCode());
        order.setOrderDetailList(detailList);
        if("1".equals(order.getDeliveryMethod())){
            WechatPickupSetting pickupSetting = pickupSettingService.selectWechatPickupSetting(order.getExtAppid());
            order.setPickupSetting(pickupSetting);
        }
        //如果是已收货 查询可进行的售后状态
        if("2".equals(order.getOrderStatus())){
            //可进行售后状态 0可退换货  1可换货 2订单关闭
            int state = 0;
            OdOrderSetting orderSetting = orderSettingService.selectOdOrderSetting(order.getExtAppid());
            //已收货多少天
            long ms = new Date().getTime() - order.getFinishTime().getTime();
            //换货
            long returnMs = orderSetting.getReturnDays().longValue()*24*60*60*1000;
            long exChangeMs = orderSetting.getExchangeDays().longValue()*24*60*60*1000;
            if(ms > exChangeMs){
                state = 2;
            }else {
                if(ms > returnMs){
                    state =1;
                }
            }
            order.setState(state);
            System.err.println("可退换货状态："+state);
        }



        return order;
    }

    /**
     * 查询订单管理列表
     * 
     * @param odOrder 订单管理
     * @return 订单管理
     */
    @Override
    public List<OdOrder> selectOdOrderList(OdOrder odOrder)
    {
        List<OdOrder> orderList = odOrderMapper.selectOdOrderList(odOrder);
        for (OdOrder order : orderList) {
            List<OdOrderDetail> detailList = orderDetailService.selectOdOrderDetailByOrderCode(order.getOrderCode());
            order.setOrderDetailList(detailList);
        }
        return orderList;
    }

    /**
     * 修改订单管理
     * 
     * @param odOrder 订单管理
     * @return 结果
     */
    @Override
    public int updateOdOrder(OdOrder odOrder)
    {
        return odOrderMapper.updateOdOrder(odOrder);
    }

    @Override
    public OdOrder selectOrderDetailById(Long id) {
        OdOrder order = odOrderMapper.selectOdOrderById(id);
        List<OdOrderDetail> orderDetailList = orderDetailService.selectOdOrderDetailByOrderCode(order.getOrderCode());
        order.setOrderDetailList(orderDetailList);
        return order;
    }

    @Override
    public OdOrder selectOdOrderByOrderCode(String orderCode) {
        return odOrderMapper.selectOdOrderByOrderCode(orderCode);
    }

    @Override
    public int todoOrderCount(String openid,String extAppid,String orderStatus,String payStatus) {
        return odOrderMapper.todoOrderCount(openid,extAppid,orderStatus,payStatus);
    }
    //
    @Override
    @Transactional
    public AjaxResult submitOrder(CheckOutModel model) {
        //商家订单设置
        OdOrderSetting orderSetting = orderSettingService.selectOdOrderSetting(model.getExtAppid());
        //查询用户未支付订单数
        int orderCount = odOrderMapper.selectUnPayOrderCount(model.getOpenid(), model.getExtAppid());
        if(orderCount>=orderSetting.getMaxUnpaid().intValue()){
            return AjaxResult.error("未支付订单到达上限！");
        }
        //立即购买
        OdOrder order = model.getOrder();
        order.setDeliveryMethod(model.getDelivery());
        //如果快递配送
        if("0".equals(order.getDeliveryMethod())){
            WechatAddress wechatAddress = order.getWechatAddress();
            order.setReceiver(wechatAddress.getContacts());
            order.setPhone(wechatAddress.getPhone());
            order.setAddress(wechatAddress.getAddress());
            order.setFullAddress(wechatAddress.getFullAddress());
            order.setAreaCode(wechatAddress.getProvince());
        }
        order.setUserRemarks(model.getRemark());
        order.setOrderCode(MakeOrderNumUtil.makeOrderNum("GD"));
        order.setCreateTime(new Date());
        order.setOrderType("0");
        odOrderMapper.insertOdOrder(order);
        //保存订单详情
        for (OdOrderDetail orderDetail : order.getOrderDetailList()) {
            orderDetail.setOrderCode(order.getOrderCode());
            //查询商品库存 并减去商品库存
            GdGoodsUnits goodsUnit = gdGoodsService.selectGoodsUnitsById(orderDetail.getGoodsUnitId());
            if(goodsUnit.getStock().intValue() >= orderDetail.getQuantity().intValue()){
                goodsUnit.setStock(goodsUnit.getStock() - orderDetail.getQuantity());
                //修改库存
                gdGoodsService.updateGdGoodsUnits(goodsUnit);
            }else {
                return AjaxResult.error(orderDetail.getGoodsName()+"库存不足！");
            }
            orderDetailService.insertOdOrderDetail(orderDetail);
        }
        //修改优惠券为已使用
        if(model.getUserCouponId() != 0){
            wechatUserCouponService.setUserCouponUsed(model.getUserCouponId());
        }
        if("cart".equals(model.getMode())){
            wechatShoppingCartService.deleteWechatShoppingCartByIds(model.getCartIds());
        }

        Map returnMap = new HashMap();

        WechatUserAccount account = userAccountService.selectWechatUserAccountByOpenId(model.getOpenid(), model.getExtAppid());
        //判断积分是否充足
        if(account.getIntegral().intValue() >= order.getIntegral().intValue()){
            //扣除积分
            if(order.getIntegral().intValue() > 0 ){ //如果使用积分
                account.setIntegral(account.getIntegral() - order.getIntegral().intValue());
                userAccountService.updateWechatUserAccount(account);
            }
        }else {
            AjaxResult.error("当前积分不足");
        }
        //支付
        if (model.getPayType().intValue() == 0) { //余额支付
            if(new BigDecimal(account.getBalance()).compareTo(new BigDecimal(order.getPayTotalAmount())) >= 0 ){
                account.setBalance((new BigDecimal(account.getBalance()).subtract(new BigDecimal(order.getPayTotalAmount()))).toPlainString());
                userAccountService.updateWechatUserAccount(account);
                //设为已支付
                order.setPayStatus("1");
                //如果自提
                if("1".equals(order.getDeliveryMethod())){
                    //直接设为待提货状态
                    order.setOrderStatus("1");
                }
                order.setBalanceAmount(order.getPayTotalAmount());
                order.setPayTime(new Date());
                this.updateOdOrder(order);
                returnMap.put("paymentMethod","0");
            }else {
                //添加到超时取消消息队列
                RabbitMqModel mqModel = new RabbitMqModel();
                mqModel.setType(0); //超时取消
                mqModel.setOrderNo(order.getOrderCode());
                rabbitMqSender.sendMessage(mqModel,orderSetting.getOrderFailureTime()*60*1000);
                return AjaxResult.error("余额不足!");
            }
        }else if(model.getPayType().intValue() == 1){ //微信支付
            //微信统一下单
            //金额转换成分
            BigDecimal price = new BigDecimal(order.getPayTotalAmount()).multiply(new BigDecimal("100"));
            price = price.setScale(0, RoundingMode.DOWN);//取整
            String payAmt = String.valueOf(price);
            returnMap = wxPayService.pay(model.getExtAppid(), model.getOpenid(),model.getIp(),order.getOrderDetailList().get(0).getGoodsName(),order.getOrderCode(),payAmt);
            returnMap.put("paymentMethod","1");
            //添加到超时取消消息队列
            RabbitMqModel mqModel = new RabbitMqModel();
            mqModel.setType(0); //超时取消
            mqModel.setOrderNo(order.getOrderCode());
            rabbitMqSender.sendMessage(mqModel,orderSetting.getOrderFailureTime()*60*1000);
        }
        return AjaxResult.success(returnMap);
    }

    @Override
    public AjaxResult pay(Long orderId, String payType, String extAppid, String openid,String ip) {
        //查询订单
        OdOrder order = this.selectOdOrderById(orderId);
        Map returnMap =new HashMap();
        if("0".equals(payType)){//余额支付
            //查询用户账户余额
            WechatUserAccount account = userAccountService.selectWechatUserAccountByOpenId(openid,extAppid);
            if(new BigDecimal(account.getBalance()).compareTo(new BigDecimal(order.getPayTotalAmount())) >= 0 ){
                account.setBalance((new BigDecimal(account.getBalance()).subtract(new BigDecimal(order.getPayTotalAmount()))).toPlainString());
                userAccountService.updateWechatUserAccount(account);
                //设为已支付
                order.setPayStatus("1");
                order.setPaymentMethod("0");
                order.setBalanceAmount(order.getTotalAmount());
                //如果自提
                if("1".equals(order.getDeliveryMethod())){
                    //直接设为待提货状态
                    order.setOrderStatus("1");
                }
                order.setPayTime(new Date());
                this.updateOdOrder(order);
                returnMap.put("paymentMethod","0");
            }else {
                return AjaxResult.error("余额不足！");
            }
        }else if("1".equals(payType)){//微信支付
            //微信统一下单
            //金额转换成分
            BigDecimal price = new BigDecimal(order.getPayTotalAmount()).multiply(new BigDecimal("100"));
            price = price.setScale(0, RoundingMode.DOWN);//取整
            String payAmt = String.valueOf(price);
            returnMap = wxPayService.pay(extAppid, openid,ip,order.getOrderDetailList().get(0).getGoodsName(),order.getOrderCode(),payAmt);
            returnMap.put("paymentMethod","1");
        }
        return AjaxResult.success(returnMap);
    }

    @Override
    public int updateOrderStatus(Long orderId, String orderStatus) {
        return odOrderMapper.updateOrderStatus(orderId,orderStatus);
    }

    //订单待评价商品列表
    @Override
    public List<OdOrderDetail> commentList(Long orderId) {
        OdOrder order = odOrderMapper.selectOdOrderById(orderId);
        List<OdOrderDetail> orderDetailList = orderDetailService.selectOdOrderDetailByOrderCode(order.getOrderCode());
        return orderDetailList;
    }

    //提交评价
    @Override
    public int commentSubmit(OdOrder order) {
        int count = 0;
        for (OdOrderDetail odOrderDetail : order.getOrderDetailList()) {
            if (odOrderDetail.getUploaded()!=null){
                String servicePicture = "";
                for (String s : odOrderDetail.getUploaded()) {
                    if(StringUtils.isEmpty(servicePicture)){
                        servicePicture = s;
                    }else {
                        servicePicture=servicePicture+","+s;
                    }
                }
                odOrderDetail.setServicePicture(servicePicture);
            }
            count=orderDetailService.updateOdOrderDetail(odOrderDetail);
        }
        return count;
    }

    //取消订单
    @Override
    @Transactional
    public int cancelOrder(Long orderId) {
        int count = 0;
        //查询订单
        OdOrder order = odOrderMapper.selectOdOrderById(orderId);
        if("0".equals(order.getPayStatus())){ //如果是未支付
            //直接更改为取消状态
            count = updateOrderStatus(orderId,"5");
            //归还用户积分
            if(order.getIntegral().intValue()>0){
                WechatUserAccount userAccount = userAccountService.selectWechatUserAccountByOpenId(order.getOpenid(),order.getExtAppid());
                userAccount.setIntegral(userAccount.getIntegral().intValue() + order.getIntegral().intValue());
                userAccountService.updateWechatUserAccount(userAccount);
            }
            //归还库存
            List<OdOrderDetail> detailList = orderDetailService.selectOdOrderDetailByOrderCode(order.getOrderCode());
            for (OdOrderDetail detail : detailList) {
                GdGoodsUnits goodsUnit = gdGoodsService.selectGoodsUnitsByGoodsIdAndUnits(detail.getGoodsId(), detail.getGoodsUnit());
                if(goodsUnit!=null){
                    goodsUnit.setStock(goodsUnit.getStock()+detail.getQuantity());
                    gdGoodsService.updateGdGoodsUnits(goodsUnit);
                }
            }

        }else if("1".equals(order.getPayStatus())){ //如果已支付
            //更改为申请取消状态待商家审核
            count = updateOrderStatus(orderId,"4");
        }
        return count;
    }

}
